package com.tegtech.core.filter;

import java.io.IOException;
import java.util.Arrays;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.tegtech.common.utils.http.RequestUriMatcher;

/**
 * 防止XSS攻击的过滤器
 * 
 * @author Jun
 */
@Component
public class XssFilter extends OncePerRequestFilter {
	
	// xss过滤开关
	@Value("${xss.enabled}")
	private boolean enabled;

	// 无需xss过滤的uri，多个用逗号隔开
	@Value("${xss.excludeUris}")
	private String excludeUris;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String requestUri = request.getRequestURI();
		
		if(!enabled || RequestUriMatcher.antMatchs(Arrays.asList(excludeUris.split(",")), requestUri)) {
			filterChain.doFilter(request, response);
			return;
		}
		XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request);
		filterChain.doFilter(xssRequest, response);
	}

}